<!-- src/views/entry/index.vue -->
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Plus, Delete, Edit, Download } from '@element-plus/icons-vue'
import { getEntryList, addEntry, updateEntry, deleteEntry, getEntryById } from '@/api/entry'
import { ElMessage } from 'element-plus'
import{ getAll}from '@/api/shop'

// 状态映射
const statusMap = {
  1: '未确认',
  2: '部分已确认',
  3: '全部确认',
  4: '拣货中',
  5: '已上架'
}

// 数据模型
const ruleForm = reactive({
  id: '',
  consignorId: '',           // 货主ID
  batchNumber: '',           // 批次号
  totalCount: '',            // 批次商品数量
  predictedArrivalTime: '',  // 预测到达时间
  warehouseId: '',           // 仓库ID
  damageCount: 0,            // 破损个数
  surpassCount: 0,           // 超出数量
  status: 1,                 // 状态
  lackCount: 0,              // 缺少数量
  saasId: '',                // SaaS标识
  createTime: '',            // 创建时间
  createBy: '',              // 创建人
  updateTime: '',            // 修改时间
  updateBy: '',              // 修改人
  isDel: 1                   // 是否删除
})

// 搜索条件
const searchForm = reactive({
  batchNumber: '',
  consignorName: '', // 货主名称（需通过接口获取）
  status: ''
})

// 表格数据
const tableData = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('新增入库单')

// 新增: 商品选择弹窗状态控制
const productDialogVisible = ref(false);

// 新增: 商品选择弹窗数据
const selectedProducts = ref([]);

// 新增: 商品搜索条件
const productSearchForm = reactive({
  name: '',
  code: ''
});

// 新增: 商品表格数据（模拟数据）
const productTableData = ref([]);
const getProducts = async () => { 
  
};

// 新增: 商品表格选中项
const productSelection = ref([]);

// 新增: 确认选择商品的方法
const confirmProductSelection = () => {
  selectedProducts.value = [...productSelection.value];
  productDialogVisible.value = false;
};

// 新增: 关闭商品选择弹窗的方法
const closeProductSelection = () => {
  productSelection.value = [];
  productDialogVisible.value = false;
};

// 新增: 商品搜索方法
const searchProducts = () => {
  // 这里应该调用实际的API搜索商品
  console.log('搜索商品:', productSearchForm);
};

// 新增: 重置商品搜索
const resetProductSearch = () => {
  productSearchForm.name = '';
  productSearchForm.code = '';
};

// 获取列表数据
const fetchList = async () => {
  
    const params = {
      batchNumber: searchForm.batchNumber,
      consignorName: searchForm.consignorName,
      status: searchForm.status,
      current: currentPage.value,
      size: pageSize.value
    }
    
    // 清理空参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    console.log('请求参数:', params)
    const res = await getEntryList(params)
    console.log('接口返回数据:', res)
    

      // 处理数据，确保时间字段被正确解析
      tableData.value = res.records.map(item => {
        return {
          ...item,
          predictedArrivalTime: item.predictedArrivalTime ? new Date(item.predictedArrivalTime) : null,
          createTime: item.createTime ? new Date(item.createTime) : null,
          updateTime: item.updateTime ? new Date(item.updateTime) : null
        }
      })
      
      // 强制刷新组件
      nextTick(() => {
        console.log('表格数据已更新:', tableData.value)
      })
      
      total.value = res.data.total || 0
      console.log('表格数据:', tableData.value)
  
 
}

// 新增
const add = () => {
  resetForm()
  dialogTitle.value = '新增入库单'
  dialogVisible.value = true
}

// 编辑
const edit = async (id) => {
  try {
    const res = await getEntryById(id)
    if (res && res.data) {
      const data = res.data
      // 处理时间字段
      Object.assign(ruleForm, {
        ...data,
        predictedArrivalTime: data.predictedArrivalTime ? new Date(data.predictedArrivalTime) : null
      })
      dialogTitle.value = '编辑入库单'
      dialogVisible.value = true
    } else {
      ElMessage.error('未获取到入库单信息')
    }
  } catch (error) {
    ElMessage.error('获取入库单信息失败')
    console.error('获取入库单信息失败:', error)
  }
}

// 删除
const remove = async (id) => {
  try {
    await deleteEntry(id)
    ElMessage.success('删除成功')
    fetchList()
  } catch (error) {
    ElMessage.error('删除失败')
    console.error('删除失败:', error)
  }
}

// 批量删除
const batchRemove = async (selection) => {
  if (selection.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  try {
    const ids = selection.map(item => item.id)
    for (const id of ids) {
      await deleteEntry(id)
    }
    ElMessage.success('删除成功')
    fetchList()
  } catch (error) {
    ElMessage.error('删除失败')
    console.error('删除失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchList()
}

// 重置
const handleReset = () => {
  searchForm.batchNumber = ''
  searchForm.consignorName = ''
  searchForm.status = ''
  fetchList()
}

// 提交表单
const submitForm = async () => {
  try {
    if (ruleForm.id) {
      await updateEntry(ruleForm)
      ElMessage.success('更新成功')
    } else {
      await addEntry(ruleForm)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    resetForm()
    fetchList()
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.response?.data?.message || error.message))
    console.error('保存失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.keys(ruleForm).forEach(key => {
    if (key === 'status') ruleForm[key] = 1
    else if (key === 'damageCount' || key === 'surpassCount' || key === 'lackCount') ruleForm[key] = 0
    else ruleForm[key] = ''
  })
}

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchList()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchList()
}

// 获取状态文本
const getStatusText = (status) => {
  return statusMap[status] || '未知'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  
  // 确保 dateTime 是字符串或日期对象
  const date = typeof dateTime === 'string' ? new Date(dateTime) : dateTime
  
  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    console.warn('无效的日期时间:', dateTime)
    return ''
  }
  
  // 格式化为 YYYY-MM-DD HH:mm:ss
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 组件挂载时获取数据
onMounted(() => {
  fetchList()
})
</script>

<template>
  <!-- 搜索区域 -->
  <div class="toolbar">
    <el-form :inline="true" :model="searchForm" >
      <el-form-item label="批次号">
        <el-input v-model="searchForm.batchNumber" placeholder="请输入批次号" clearable />
      </el-form-item>
      <el-form-item label="货主名称">
        <el-input v-model="searchForm.consignorName" placeholder="请输入货主名称" clearable />
      </el-form-item>
     

      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button type="primary" @click="add" style="margin-left: 10px;">新增</el-button>
  </div>

  <!-- 表格 -->
  <div class="table-container">
    <el-table :data="tableData"  border style="width: 100%">
      
      <el-table-column type="index" label="#" width="50" />
      <el-table-column prop="batchNumber" label="批次号" width="180" />
      <el-table-column prop="consignorName" label="货主" width="120" />
       <el-table-column prop="predictedArrivalTime" label="预测到达时间" width="160">
        <template #default="scope">
          <span>{{ formatDateTime(scope.row.predictedArrivalTime) }}</span>
        </template>
      </el-table-column>
      
     
      
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="edit(scope.row.id)"  >修改</el-button>
          <el-button link type="primary" icon="Delete" @click="remove(scope.row.id)"  >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页 -->
  <div class="pagination">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="600px"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="{
        batchNumber: [{ required: true, message: '请输入批次号', trigger: 'blur' }],
        consignorId: [{ required: true, message: '请输入货主ID', trigger: 'blur' }],
        predictedArrivalTime: [{ required: true, message: '请选择预测到达时间', trigger: 'change' }]
      }"
      label-width="auto"
      style="max-width: 800px"
    >
      <el-form-item label="货主名称" prop="consignorName">
        <el-input v-model.number="ruleForm.consignorName" placeholder="请输入货主名称" />
      </el-form-item>
      <el-form-item label="批次" prop="batchNumber">
        <el-input v-model="ruleForm.batchNumber" placeholder="请输入批次" />
      </el-form-item>
      <el-form-item label="预计到达时间" prop="predictedArrivalTime">
        <el-date-picker
          v-model="ruleForm.predictedArrivalTime"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <!-- 弹窗中的新增按钮 -->
      <el-form-item label="商品" style="margin-bottom: 0;">
        <el-button type="primary" size="small" @click="productDialogVisible = true">
          <Plus />
          添加商品
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 新增: 商品选择弹窗 -->
  <el-dialog
    v-model="productDialogVisible"
    title="选择商品"
    width="800px"
  >
    <!-- 商品搜索区域 -->
    <el-form :inline="true" :model="productSearchForm" @submit.prevent="searchProducts">
      <el-form-item label="商品名称">
        <el-input v-model="productSearchForm.name" placeholder="请输入商品名称" clearable />
      </el-form-item>
      <el-form-item label="规格编码">
        <el-input v-model="productSearchForm.code" placeholder="请输入规格编码" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchProducts">搜索</el-button>
        <el-button @click="resetProductSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 商品表格 -->
    <el-table 
      :data="productTableData" 
      border 
      style="width: 100%" 
      ref="productTable"
      @selection-change="productSelection = $event"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="code" label="规格编码" />
      <el-table-column prop="spec" label="规格" />
    </el-table>

    <!-- 弹窗底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeProductSelection">取消</el-button>
        <el-button type="primary" @click="confirmProductSelection">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
  padding: 0 20px;
}

.table-container {
  margin: 0 auto;
  width: 100%;
  max-width: 1200px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  text-align: center;
  padding: 0 20px;
}

.el-table-column {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 10px;
  }
  .el-input {
    width: 100%;
    margin-right: 0;
  }
}
</style>